package com.learn.kotlinlearndemolist.ui

import android.os.Bundle
import androidx.fragment.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.databinding.DataBindingUtil
import androidx.recyclerview.widget.LinearLayoutManager
import com.learn.kotlinlearndemolist.model.Fruit
import com.learn.kotlinlearndemolist.R
import com.learn.kotlinlearndemolist.databinding.FragmentSecondBinding
import com.learn.kotlinlearndemolist.listview.FruitListAdapter
import com.learn.kotlinlearndemolist.listview.FruitRecAdapter

class SecondFragment : Fragment() {

    private lateinit var mBinding: FragmentSecondBinding
    private lateinit var mFruitList: MutableList<Fruit>
    private val data =
        listOf(
            "Orange", "Apple", "Banana", "Watermelon", "pear", "Strawberry", "Mango",
            "Orange", "Apple", "Banana", "Watermelon", "pear", "Strawberry", "Mango"
        )

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View {
        // Inflate the layout for this fragment
        mBinding = DataBindingUtil.inflate(
            LayoutInflater.from(requireContext()),
            R.layout.fragment_second,
            container,
            false
        )
        return mBinding.root
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        initData()
        initView()
    }

    private fun initView() {
        val fruitAdapter =
            FruitListAdapter(requireActivity() as AppCompatActivity, R.layout.list_item, mFruitList)
        mBinding.listView.adapter = fruitAdapter
        mBinding.listView.setOnItemClickListener { _, _, position, _ ->
            val fruit = mFruitList[position]
            Toast.makeText(requireContext(), fruit.name, Toast.LENGTH_SHORT).show()
        }
        val fruitRecAdapter = FruitRecAdapter(mFruitList)
        val layoutManager = LinearLayoutManager(requireContext())
        layoutManager.orientation = LinearLayoutManager.VERTICAL
        mBinding.recView.layoutManager = layoutManager
        mBinding.recView.adapter = fruitRecAdapter
    }

    private fun initData() {
        mFruitList = mutableListOf()
        for (fruit in data) {
            mFruitList.add(Fruit(fruit, R.drawable.ic_launcher_background))
        }
    }

}